package com.example.demo.producer_consumer;

public class Wait_Notify {

    private static String LOCK = "lock";

    private static Integer count = 0;

    private static final Integer FULL = 10;


    class Producer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
                synchronized (LOCK){
                    while (count.equals(FULL)){
                        try {
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName() + "生产者生产，目前总共有" + count);
                    LOCK.notifyAll();
                }
            }
        }
    }

    class Consumer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                        Thread.sleep(1000);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
                synchronized (LOCK){
                    while (count.equals(0)){
                        try {
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName() + "消费者消费，目前总共有" + count);
                    LOCK.notifyAll();
                }
            }
        }
    }

    public static void main(String[] args) {
        Wait_Notify wait_notify = new Wait_Notify();
        Producer producer = wait_notify.new Producer();
        Consumer consumer = wait_notify.new Consumer();

        new Thread(producer, "producer1").start();
        new Thread(producer, "producer2").start();
        new Thread(producer, "producer3").start();
        new Thread(consumer, "consumer1").start();
        new Thread(consumer, "consumer2").start();
        new Thread(consumer, "consumer3").start();

    }
}
